#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 1e3 + 10;
vector<int>a[N];
int f[4][N];
int n, m;
int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		int x;
		cin >> x;
		a[x % m].push_back(x);
	}
	memset(f, -0x3f, sizeof(f));
	f[0][0] = 0;
	for (int i = 0; i < m; i++) {
		sort(a[i].begin(), a[i].end());
		reverse(a[i].begin(), a[i].end());
		for (int j = 0; j < 3 && a[i].size(); j++) {
			int x = a[i][j];
			for (int z = 3; z >= 1; z--) {
				for (int k = 0; k < m; k++) {
					f[z][k] = max(f[z][k], f[z - 1][(k - x % m + m) % m] + x);
				}
			}
		}
	}
	cout << f[3][0] << endl;
	return 0;
}